package com.bop.dehong.decaifu;

import java.util.TreeMap;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import cn.jpush.android.api.JPushInterface;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.DeviceUuidFactory;
import com.base.dehong.util.LogUtils;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.StringUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.base.TopManager;
import com.bop.dehong.bid.MyBidActivity;
import com.bop.dehong.center.RechargeActivity;
import com.bop.dehong.config.Config;
import com.bop.dehong.info.entity.ToubiaoEntity;
import com.bop.dehong.info.entity.ToubiaoItemEntity;
import com.bop.dehong.info.entity.ToubiaoShouyiEntity;
import com.bop.dehong.info.entity.UserEntity;
import com.bop.dehong.http.model.GetUserInfoModel;
import com.bop.dehong.http.model.ToubiaoModel;
import com.bop.dehong.http.model.ToubiaoshouyiModel;
import com.bop.dehong.info.UserInfo;
import com.bop.dehong.login.LoginActivity;
import com.bop.dehong.setting.NameAuthActivity;
import com.bop.dehong.util.CommonDialog;
import com.bop.dehong.util.CommonDialog.OnLeftClickListener;
import com.bop.dehong.util.WebUrlUtil;
import com.bop.dehong.webview.WebViewActivity;
import com.bop.dehong.widget.RoundProgressBar;

public class ToubiaoActivity extends BaseActivity {
	private ToubiaoModel toubiaoModel;
	private ToubiaoshouyiModel toubiaoshouyiModel;
	private String id;
	private String uid, price, voucher, maxvoucher;
	private TextView toubiao_rate, toubiao_money, toubiao_time;
	private RoundProgressBar toubiao_count;
	private TextView toubiao_annual_revenue;
	private TextView toubiao_btn;
	private EditText toubiao_avaliblemoney, toubiao_coin; 
	private Float avaliblemoney = 0.0f, surplus = 0.0f; //rate;
	private int min, myvoucher;
	private LinearLayout ll_toubiao_coin, mViewLayout;
	private String tip;
	private Dialog toubiaoDialog; 
	private Long local;
	private GetUserInfoModel mGetInfoModel;
	private TopManager manager;
	
	@Override
	protected void initTop() {
		String title = getIntent().getExtras().getString(Config.CAT_NAME);
		View mView = getView(R.id.toubiao_top);
		manager = new TopManager(mView);
		manager.setTitle(title);
		manager.setLeftImageVisibility(View.VISIBLE);
		manager.setRightTextVisibility(View.VISIBLE);
		manager.setRightText("详情");
		manager.setRightTextOnClick(this);
	}
	
	@Override
	protected void initUI() {
		id = getIntent().getExtras().getString(Config.CAT_ID);
		if (DeHongApp.mLoginEntity != null) {
			uid = DeHongApp.mLoginEntity.getUid();
		}else {
			uid = "";
		}
		mViewLayout = getView(R.id.view_layout);
		ll_toubiao_coin = getView(R.id.ll_toubiao_coin);
		toubiao_rate = getView(R.id.toubiao_rate);
		toubiao_money = getView(R.id.toubiao_money);
		toubiao_time = getView(R.id.toubiao_time);
		toubiao_count = getView(R.id.toubiao_count_roundprobar);
		toubiao_avaliblemoney = getView(R.id.toubiao_avaliblemoney);
		toubiao_annual_revenue = getView(R.id.toubiao_annual_revenue);
		toubiao_coin = getView(R.id.toubiao_coin);
		toubiao_btn = getView(R.id.toubiao_btn);
		registerOnClickListener(toubiao_btn,mViewLayout);
		toubiao_avaliblemoney.setOnFocusChangeListener(new android.view.View.
				OnFocusChangeListener() {
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				price = getStr4TextView(toubiao_avaliblemoney); 
				if (StringUtils.isNotEmpty(price) && !hasFocus && !toubiao_btn.hasFocus()) {
						// 此处为失去焦点时的处理内容
				       getShouyi();	
					}
				}
		});
		toubiao_coin.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				 voucher = getStr4TextView(toubiao_coin);
//				 price = getStr4TextView(toubiao_avaliblemoney);
				if (StringUtils.isNotEmpty(voucher) && !hasFocus) {
					 if (StringUtils.isNotEmpty(maxvoucher)) {
						 if (StringUtils.isNotEmpty(uid) && Integer.valueOf(voucher) > myvoucher) {
							 showDialog("投标德鸿币不能大于您的德鸿币！");
						        return;
						}
						 if (StringUtils.isNotEmpty(price) && Integer.valueOf(voucher) > Integer.valueOf(maxvoucher)) {
							 showDialog("投标" + price + "元只能使用" + maxvoucher + "德鸿币！");
						        return;
						}
					}else {
						return;
					}
					 getShouyi();
				}
			}
		});
	}
	 /**
	 * 提示
	 */
	 @SuppressLint("NewApi")
	 private void showDialog(String msg){ 
	    	toubiaoDialog = new Dialog(this, R.style.MyDialogStyle);
			View view = View.inflate(this, R.layout.dialog_re_login, null);
			toubiaoDialog.setContentView(view);
			toubiaoDialog.setCancelable(false);
			TextView msgtv = getView(view, R.id.textView2);
			msgtv.setText(msg);
			Button loginBtn = getView(view, R.id.re_login);
			loginBtn.setText("确定");
			registerOnClickListener(loginBtn);
			toubiaoDialog.show();
	  }  
	
	    /**
		 * 投标
		 */
		private void getBidDialog() {
			CommonDialog dialog = new CommonDialog(this);
			dialog.showDialog("您是否确定投标？");
			dialog.setOnLeftClickListener(new OnLeftClickListener() {

				@Override
				public void setOnClickLeftResult() {
					Intent intent = new Intent(ToubiaoActivity.this, WebViewActivity.class);
	     			intent.putExtra("title", "投标");
	     			intent.putExtra("url", getUrl());
	     			intent.putExtra(Config.GO_BACK, true);
	     			startActivityForResult(intent, 101);
				}
			});
		}
	    
	    /**
	     * 判断投标金额
	     */
	    private boolean judge() {
	    	if (TextUtils.isEmpty(price)) {
	 			ToastUtils.show(ToubiaoActivity.this, "请输入金额");
	 			return false;
	 		}else {
	 			Float investmoney =  Float.parseFloat(price);
		        if (investmoney > surplus) {
					showDialog("投标金额不能大于可投金额,请重新输入！");
			        return false;
				}
		        if (investmoney < min || investmoney <= 0) {
					showDialog("投标金额必须大于最小投标额" + min + "！");
			        return false;
				}
		        if (investmoney % min != 0) {
		        	showDialog("投标金额为最小投标额" + min + "的整数倍数,请重新输入!");  
			        return false;
				}
			}
	    	return true;
		}
	    
	
	private String getUrl() {
		TreeMap<String, String> postValues = new TreeMap<String, String>();
		postValues.put("a", "investupdate");
		postValues.put("id", id);
		postValues.put("m", "Invest");		
		postValues.put("price", price);
		postValues.put("uid", uid);
		postValues.put("voucher", voucher);
		String device_code = "";
		device_code = JPushInterface.getRegistrationID(this);//传RegistrationID方便后台根据指定RegistrationID推送消息
		DeviceUuidFactory factory = new DeviceUuidFactory(this);
//		device_code = factory.getDeviceUuid() + "";
		LogUtils.e(TAG + ",device_code", "registrationId=" + device_code);
		String phone_type = factory.getPhoneType();
		postValues.put("phone_type", phone_type);
		postValues.put("device_code", device_code);
		postValues.put("platform", "android");
		return WebUrlUtil.getWebUrl(this, Config.getIP() + Config.getBid(), postValues);
	}

	@Override
	protected void initData() {
		request();
	}

	private void request() {
		showProgressDialog();
		if (toubiaoModel == null) {
			toubiaoModel = new ToubiaoModel(this, callback);
		}
		toubiaoModel.doNet(id, uid);
	}

	RequestCallBack<ToubiaoEntity> callback = new RequestCallBack<ToubiaoEntity>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}
		
		public void onSuccess(ToubiaoEntity info) {
			super.onSuccess(info);
			ToubiaoItemEntity item = info.getList().getItem();
			manager.setTitle(item.getTitle());
			UserEntity users = info.getList().getUsers();
			toubiao_rate.setText(item.getRates());
			toubiao_money.setText(item.getMoney());
			toubiao_time.setText(item.getDeadlines());
			
			toubiao_count.setProgress(item.getPercent());
			toubiao_count.setTitleName("人购买");
			toubiao_count.setCount(info.getList().getCount());
			int state = Integer.valueOf(item.getState());
			switch (state)
			{
			case 1:
//				toubiao_count.setTitleName("招标中");
				break;
			case 5:
//				toubiao_count.setTitleName("已满标");
				tip = "此标已满标，请选择其他优质标!";
				cannotBit();
				break;
			case 7:
//				toubiao_count.setTitleName("还款中");
				tip = "此标还款中，请选择其他优质标!";
				cannotBit();
				break;
			case 9:
//				toubiao_count.setTitleName("已还清");
				tip = "此标已还清，请选择其他优质标!";
				cannotBit(); 
				break;
			case 12:
//				toubiao_count.setTitleName("预招标");
				tip = "此标预招标中，请选择其他优质标!";
				cannotBit();
				break;
			default:
				break;
			}
			toubiao_avaliblemoney.setHint("可用余额： " + users.getMoney());
			if (StringUtils.isNotEmpty(users.getVoucher())) {
				myvoucher = Integer.valueOf(users.getVoucher());
			}
			toubiao_coin.setHint("可用德鸿币： " + myvoucher);
			avaliblemoney = Float.valueOf(users.getMoney());//可投金额
			String toubiaouid = item.getUid();
			if (TextUtils.equals(toubiaouid, uid)) {
				tip = "本人发的标，不能投自己的标!";
				cannotBit();
			}
			//判断是不是新手标
			String isnew = item.getIsnew();
			if (TextUtils.equals(isnew, "1")) {
				int hadloan = users.getHadloan();
				if (hadloan > 0) {
					tip = "体验标只适用于还未参与投资的新用户，您是老用户，请关注德鸿其他优质标的吧！";
					cannotBit();
				}
			}
			String use_voucher = item.getUse_voucher();
			if (TextUtils.equals(use_voucher, "1")) {
				ll_toubiao_coin.setVisibility(View.VISIBLE);
			}else {
				ll_toubiao_coin.setVisibility(View.GONE);
			}
//			rate = Float.valueOf(item.getRates()) / 100;
			if (StringUtils.isNotEmpty(item.getSurplus())) {
				surplus = Float.valueOf(item.getSurplus());	
			}
			min = Integer.valueOf(item.getMin());
		};
		
	};
	
	/*
	 * 计算收益
	 */
	private void getShouyi() {
		showProgressDialog();
		if (toubiaoshouyiModel == null) {
			toubiaoshouyiModel = new ToubiaoshouyiModel(this, callback1);
		}
		toubiaoshouyiModel.doNet(id, uid, price, voucher);
	}
	
	RequestCallBack<ToubiaoShouyiEntity> callback1 = new RequestCallBack<ToubiaoShouyiEntity>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(ToubiaoShouyiEntity info) {
			maxvoucher = info.getVoucher();
			toubiao_annual_revenue.setText(StringUtils.getFormatValue(info.getInterest()));
			super.onSuccess(info);
		}
		
	};
	
	/*
	 * 不能投标时可以点击弹出提示语
	 */
	@SuppressLint("NewApi")
	private void cannotBit() {
		toubiao_btn.setBackground(getResources().getDrawable(R.drawable.bg_btn_grey));
		toubiao_avaliblemoney.setFocusable(false);
		toubiao_coin.setFocusable(false); 
//		toubiao_btn.setClickable(false);
	}
	
	@Override
	protected int getContentViewId() {
		TAG = getClass().getName();
		return R.layout.activity_toubiao;
	}

	private void reqInfo(){
		showProgressDialog();
		if (mGetInfoModel == null) {
			mGetInfoModel = new GetUserInfoModel(this, getCallback);
		}
		local = System.currentTimeMillis() / 1000;
		mGetInfoModel.doNet(DeHongApp.mLoginEntity.uid);
	}
	
	RequestCallBack<UserInfo> getCallback = new RequestCallBack<UserInfo>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(UserInfo info) {
			super.onSuccess(info);
			Long net = info.stamp;
			Long modify = net - local;
			if (Math.abs(modify) >= 300) {
				PreferencesUtils.putLong(ToubiaoActivity.this, Config.TAG, modify);	
			}
			DeHongApp.mUserInfo = info;
			avaliblemoney = Float.valueOf(DeHongApp.mUserInfo.total_money);//可投全部金额
		}
		
	};
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == 100) {
			if (DeHongApp.mLoginEntity != null) {
				uid = DeHongApp.mLoginEntity.getUid();
			}else {
				uid = "";
			}
		}else if (requestCode == 101) {
			ToastUtils.show(this, "投标成功！");
			reqInfo();//投标成功后刷新个人信息
			new Handler().postDelayed(new Runnable() {
				@Override
				public void run() {
					openActivity(MyBidActivity.class);
				}
			}, 1000);
		}else if (requestCode == 102 || requestCode == 103) {
			reqInfo();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (toubiaoDialog != null) {
    		toubiaoDialog.dismiss();
    		toubiaoDialog = null;
		}
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.top_bar_right_txt:
			Bundle bundle = new Bundle();
			bundle.putString(Config.CAT_ID, id);
			openActivity(DeCaifuActivity.class, bundle);	
			break;

		case R.id.toubiao_btn:
			price = getStr4TextView(toubiao_avaliblemoney);
			voucher = getStr4TextView(toubiao_coin);
			if (StringUtils.isNotEmpty(uid)) {
				int mCertification = Integer.valueOf(DeHongApp.mLoginEntity.certification);
				if (mCertification == 2){
					if (StringUtils.isNotEmpty(tip)) {
						showDialog(tip);
						return;
					}
					if (!judge()) {
						return;
					};     
					Float investmoney =  Float.parseFloat(price);
				     if (investmoney > avaliblemoney) {
				        ToastUtils.showLong(this, "投标金额不能大于您的余额,请充值！"); 
						Intent intent = new Intent(ToubiaoActivity.this, RechargeActivity.class);
						 startActivityForResult(intent, 103);
				        return;
				     } 
				     if (TextUtils.isEmpty(voucher)) 
				     {
							voucher = "";
					}else
					if (StringUtils.isNotEmpty(maxvoucher)) 
					{
						if (Integer.valueOf(voucher) > myvoucher) 
						{
							showDialog("投标德鸿币不能大于您的德鸿币！");
							return;
						}
						if (StringUtils.isNotEmpty(price) && Integer.valueOf(voucher) > Integer.valueOf(maxvoucher)) {
							showDialog("投标" + price + "元只能使用" + maxvoucher + "德鸿币！");
							return;
						}
					}
					getBidDialog();	
				}else if (mCertification == 0){
					ToastUtils.showLong(this, "你还未实名认证，请先实名认证再投标！");
					Intent intent3 = new Intent(ToubiaoActivity.this, NameAuthActivity.class);
					intent3.putExtra(Config.UID, uid);
					startActivityForResult(intent3, 102);
					return;
				}else {
					showDialog("实名认证中，请等待！");
					 return;
				}
			}else {
				ToastUtils.showLong(this, "你还未登录，请先登录再投标！");
				Intent intent = new Intent(ToubiaoActivity.this, LoginActivity.class);
				intent.putExtra(Config.GO_BACK, true);
				startActivityForResult(intent, 100);
				return;
			}
			
			break;
		case R.id.view_layout:
			toubiao_avaliblemoney.clearFocus();
			toubiao_coin.clearFocus();
			break;
		case R.id.re_login:
			if (toubiaoDialog != null) {
	    		toubiaoDialog.dismiss();
	    		toubiaoDialog = null;
			}
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
	
}
